const { resolve } = require('../resolve');

const { Buffer } = require('buffer');

const Path = require('path');

function pack(opt, code) {
    return `zpack.define(${JSON.stringify(opt)},function(require,exports,module,__dirname,__filename){ ${code || ''} \n\n})`;
}


function CommonJsLoader(module, opt) {
    let loc = resolve(Path.dirname(module.file.path), module.file.path, opt);
    let codeOpt = {
        id: loc.url,
        dependency: {}
    };
    for (let dep in module.dependency) {
        codeOpt.dependency[dep] = module.dependency[dep].url;
    }
    module.file.path = loc.target; 
    module.opt = codeOpt;    
    module.file.contents = new Buffer(pack(codeOpt, module.code));
    return module;
}

module.exports = CommonJsLoader;
